<!-- 能源消耗明细 -->
<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <WeekSelect ref="searchRef" @search="handleSearch"></WeekSelect>

    <div class="sub-content-box">

      <div class="column-box">
        <div style="width: 100%;text-align:right;margin-right: 15px;"> <a-button type="primary" @click="handleExport"
            :loading="exportLoading">导出</a-button></div>
        <div class="chart-box" v-for="(item, index) in lineTypeList" :key="item.dictCode">
          <Pie v-if="index == 0" :loading="item.loading" :legendExist="false" :chartData="item.chartData"
            :title="item.itemName" />
          <Bar v-else-if="index == 4" :loading="item.loading" :chartData="item.chartData" :title="item.itemName" />
          <Bar v-else :loading="item.loading" :chartData="item.chartData" :title="item.itemName" />
        </div>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup>
import Pie from '@/components/Charts/Pie/normalPie.vue'
import Bar from '@/components/Charts/Bar/index.vue'
import { ref, onMounted, watch, computed } from 'vue'
import { PageWrapper } from '@/components/Page'
import { getWeeklyReportChartData, getWeeklyDatachainData, getWeeklyTotalDatachainData } from '@/api/common/chart'
import { getDictListByCode } from '@/api/sys/dict'
import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
import { getBarData } from '@/api/carbon/calc'
import { getYearWeek, getLastWeek } from '@/utils/dateUtil'
import WeekSelect from './WeekSelect.vue'
import { GeneralWeeklyExportData } from '@/api/common/chart.ts'
import {
  downloadByData,
} from '@/utils/file/download';

defineOptions({ name: 'WeeklyReport' })

const exportLoading = ref(false)
const dictCode = 'air_conditioner_week_report'
const lineTypeList = ref([])
const pieTypeList = ref([])
const chartList = ref([])
const dataReady = ref(false)
const searchRef = ref()
const searchInfo = ref();

onMounted(() => {
  searchRef.value.handleSearch()
})

onMounted(async () => {
  getTypeList()
})
const handleExport = async () => {
  // searchInfo.value.dictCode = "air_conditioner_week_report"
  // searchInfo.value.itemName = "周报"
  exportLoading.value = true
  const sear = {
    dictCode: 'air_conditioner_week_report',
    queryType: 'week',
    startDay: searchInfo.value.endDay,
    lastStartDay: searchInfo.value.startDay,
    itemName: '周报'
  }
  const { data, headers } = await GeneralWeeklyExportData(sear)
  let contentDisposition = decodeURIComponent(headers["content-disposition"]);
  const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
  const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
  downloadByData(data, fileName);
  exportLoading.value = false
  message.success("导出成功");
}
const handleSearch = async (params) => {
  searchInfo.value = params
  console.log(searchInfo.value, 'searchInfo.value');

  lineTypeList.value.length && resetData();
}

// 重组数据列表
const getTypeList = async () => {
  const res = await getDictListByCode(dictCode)
  dataReady.value = true
  lineTypeList.value = res.map((item, index) => {
    if (index === 0) {
      return {
        ...item,
        itemName: '本周各系统能耗对比',
        fun: getWeeklyReportChartData,
        loading: true,
        chartData: []
      }
    } else return {
      ...item,
      loading: true,
      chartData: [],
      fun: getWeeklyDatachainData
    }
  })
  // 添加空调科上周及本周能耗对比到数组的第五个位置
  lineTypeList.value.splice(4, 0, {
    ...res[0],
    itemName: '空调科上周及本周能耗对比',
    fun: getWeeklyTotalDatachainData,
    loading: true,
    chartData: []
  })
  // console.log(lineTypeList.value)
}

watch(
  () => lineTypeList.value,
  () => {
    if (lineTypeList.value.length > 0) {
      resetData()
    }
  },
  { immediate: true },
)
// 初始化数据
const resetData = async () => {
  lineTypeList.value.forEach((item, index) => {
    getChartChildListData(item, index);
  })
}

// 获取子项数据
const getChartChildListData = async (item, index) => {
  const lastWeek = searchInfo.value.startDay
  console.log(lastWeek, "lastWeek");

  const currentWeek = searchInfo.value.endDay
  console.log(currentWeek, 'currentWeek');

  // 空调科上周及本周能耗对比
  if (index === 0) {
    assignChartData(item, {
      dictCode,
      itemName: '空调科上周及本周能耗对比',
      queryType: 'week',
      // startDay: '2025-03'
      startDay: currentWeek
    }, index)
  } else {
    assignChartData(item, {
      dictCode,
      itemName: item.itemName,
      // startDay: '2025-03',
      // lastStartDay: '2025-02'
      startDay: currentWeek,
      lastStartDay: lastWeek
    }, index)
  }
}

const assignChartData = (item, params, index) => {
  item.fun(params)
    .then((res) => {
      if (index == 0) {
        item.chartData = res
      } else if (index == 4) {
        item.chartData = formateArrayNumberFour(res)
      }
      else {
        item.chartData = formateBarData(res)
      }
    })
    .finally(() => {
      item.loading = false
    })
}

// 右侧6个图表数据格式化
const formateBarData = (params) => {
  let ret = {
    xaxisList: params.headers,
    yaxisList: [{
      name: '上周',
      data: Object.values(params.bodyList[0].oldData)
    }, {
      name: '本周',
      data: Object.values(params.bodyList[0].curData)
    }],
    // , {
    //   name: '增长率',
    //   data: Object.values(params.bodyList[0].radio)
    // }],
    // grid: {
    //   bottom: '60%',  // 调整图表下边距
    //   top: '10%',
    // },
    xAxis: {
      axisLabel: {
        formatter: function (value) {
          return value;
        }
      }
    },
    table: {
      show: true,
      bottom: '8px',   // 调整表格位置
      left: '12px',
      width: `calc(100% - 24px)`,
      data: [
        Object.values(params.bodyList[0].curData),
        Object.values(params.bodyList[0].oldData),
        // Object.values(params.bodyList[0].radio)
      ],
      // header: false,
      header: {
        backgroundColor: '#f5f5f5',
        fontWeight: 'bold',
      },
      cellStyle: {
        borderColor: '#ddd',
        borderWidth: 1,
        padding: 8,
        width: `${100 / 7}%`,
        textAlign: 'center'
      }
    }
  }
  return ret;
}

// 第5个表数据格式化
const formateArrayNumberFour = (params) => {
  let ret = {
    xaxisList: params.headers,
    yaxisList: [{
      name: '',
      data: [
        params.bodyList[0].oldData[params.headers[0]],
        params.bodyList[0].curData[params.headers[1]],
        // params.bodyList[0].ratio[params.headers[2]],
      ]
    }]
  }
  return ret;
}

</script>

<style scoped lang="scss">
.sub-content-box {
  height: 100%;
  overflow: auto;

  .column-box {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    height: 100%;
  }

  .chart-box {
    box-sizing: border-box;
    width: 25%;
    height: 50%;
    padding: 4px;
  }
}
</style>
